package com.xfb.user.config;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * @Auther: Xing Fang Bin
 * @Date: 2021/10/30/12:04
 * @Description:
 */
public class MailUtil {

    private static JavaMailSenderImpl javaMailSender;

    private static final String SENDER = "936270749@qq.com";

    static {
        javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost("smtp.qq.com");// 链接服务器
//        javaMailSender.setPort(25);// 默认使用25端口发送
        javaMailSender.setUsername("936270749@qq.com");// 邮箱账号
        javaMailSender.setPassword("hpbgewtsitspbead");// 授权码
        javaMailSender.setDefaultEncoding("UTF-8");
//        javaMailSender.setProtocol("smtp");

//        Properties properties = new Properties();
//        properties.setProperty("mail.debug", "true");// 启用调试
//        properties.setProperty("mail.smtp.timeout", "1000");// 设置链接超时
//        设置通过ssl协议使用465端口发送、使用默认端口（25）时下面三行不需要
//        properties.setProperty("mail.smtp.auth", "true");// 开启认证
//        properties.setProperty("mail.smtp.socketFactory.port", "465");// 设置ssl端口
//        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

//        javaMailSender.setJavaMailProperties(properties);
    }

    public static void main(String[] args) throws Exception {
        sendSimpleMail(new String[]{"xing936270749@163.com"}, "邮件主题", "邮件内容", false);
    }

    /**
     * 发送普通邮件
     *
     * @param to 收件人
     * @param subject 主题
     * @param text 正文
     * @param isHtml 正文是否为html格式
     */
    public static void sendSimpleMail(String[] to, String subject, String text, boolean isHtml)  {
        MimeMessage message = null;
        try {
            message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SENDER, "通知");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, isHtml);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        javaMailSender.send(message);
    }
}